package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.api.CommonConfig;
import com.fgs.common.entity.CommonDataListInfo;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.qrcode.CustomCaptureActivity;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.dialog.OperateTipDialog;
import com.google.gson.Gson;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.api.OrderApiService;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.constant.OrderType;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.GoodsModel;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.BoHuiBodyBean;
import com.tianhui.consignortwofei.mvp.model.enty.ConsignorInfo;
import com.tianhui.consignortwofei.mvp.model.enty.GoodsInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderOperateInfo;
import com.tianhui.consignortwofei.mvp.model.enty.ToExamineInfo;
import com.tianhui.consignortwofei.mvp.model.enty.UserInfo;
import com.tianhui.consignortwofei.mvp.model.enty.YuQiTipInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.DriverCarStatisticalInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.OrderStatisticalInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.StatisticsDataInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.ConsignorListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.FindCarDeliveryListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.FindCarOnlyLookActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.LiuLanLogActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderDetailActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderOperateActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OverdueManageActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.TongHuaLogActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.VehicleFrontActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.lite.CarSearchAuditActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.lite.EditFindCarLiteDeliverActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.display.DisplayDataActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.SourceDocumentListAdapter;
import com.tianhui.consignortwofei.mvp.ui.adapter.ToExamineListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderOprate.OrderOperateCallback;
import com.tianhui.consignortwofei.pattern.orderOprate.OrderRequestOperate;
import com.tianhui.consignortwofei.pattern.orderStatus.status.IOrderStatus;
import com.tianhui.consignortwofei.pattern.orderStatus.status.impl.SourceStatus;
import com.tianhui.consignortwofei.role.RoleController;
import com.tianhui.consignortwofei.widget.ArcTextView;
import com.tianhui.consignortwofei.widget.AuthStatusView;
import com.tianhui.consignortwofei.widget.GradientsTextView;
import com.tianhui.consignortwofei.widget.OrderOperateView;
import com.tianhui.consignortwofei.widget.QRCodeDialog;
import com.tianhui.consignortwofei.widget.StatisticsDataView;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.enums.ThreadType;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.security.Base64Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;
import org.yczbj.ycrefreshviewlib.item.RecycleViewItemLine;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * @author fgs
 * @date 2020/8/31
 * @description
 **/
public class HomeFragment extends BaseFragment {
    @BindView(R.id.fragment_home_swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.fragment_home_vehicleTotalNumberTextView)
    GradientsTextView mVehicleTotalNumberTextView;
    @BindView(R.id.fragment_home_tipTextView)
    ArcTextView mTipTextView;
    @BindView(R.id.fragment_home_authStatusView)
    AuthStatusView mAuthStatusView;

    @BindView(R.id.fragment_home_orderOperateView)
    OrderOperateView mOperateView;
    @BindView(R.id.fragment_home_statisticsDataView)
    StatisticsDataView mStatisticsDataView;


    @BindView(R.id.ll_putong_send)
    LinearLayout ll_putong_send;
    @BindView(R.id.ll_zhaoche_send)
    LinearLayout ll_zhaoche_send;
    @BindView(R.id.ll_youzhi_send)
    LinearLayout ll_youzhi_send;

    @BindView(R.id.tv_qrcode_scan)
    TextView tv_qrcode_scan;

    @BindView(R.id.tv_toolbar_title)
    TextView tv_toolbar_title;

    @BindView(R.id.iv_more)
    TextView iv_more;
    @BindView(R.id.tv_all_num)
    TextView tv_all_num;


    //fragment
//    @BindView(R.id.rl_input_fragment)
//    RelativeLayout rl_input_fragment;

    //列表
    @BindView(R.id.layout_data_list_recyclerView)
    YCRefreshView mRecyclerView;


    protected RecyclerArrayAdapter mAdapter;
    private int mPage = 1;
    private int mTotalPage;
    private boolean isRefresh;
    private IOrderStatus mIOrderStatus;


    private UserInfoModel mUserInfoModel;
    private final StatisticsDataInfo statisticsDataInfo = new StatisticsDataInfo();
    private String userAccount="";
    private int rolePosition;

    public static boolean firstShow=true;

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected CommonView createView() {
        return null;
    }

    @Override
    protected CommonPresenter createPresenter() {
        return null;
    }

    @Override
    protected void init() {

        tv_toolbar_title.setText("首页");

        mUserInfoModel = new UserInfoModel();
        requestVehicleNearby();
        refreshStatisticsView();

        mOperateView.setOperateInfoList(getOperateList());
        mOperateView.setOnOrderOperateClickListener(new OrderOperateView.OnOrderOperateClickListener() {
            @Override
            public void onOperateClick(Context context, TextView textView, int position, OrderOperateInfo operateInfo) {

                switch (position) {
                    case OrderOperateView.OPERATE_TOP_LEFT:
                        RoleController.getInstance().sourceOperate();

                        break;
                    case OrderOperateView.OPERATE_TOP_RIGHT:
                        RoleController.getInstance().dispatchOperate();

                        break;
                    case OrderOperateView.OPERATE_BOTTOM_LEFT:
                        RoleController.getInstance().freightOperate();

                        break;
                    case OrderOperateView.OPERATE_BOTTOM_RIGHT:

                        RoleController.getInstance().paymentOperate();
                        break;
                    case OrderOperateView.OPERATE_CENTER:
                        RoleController.getInstance().deliverGoodsOperate();
                        break;
                }


            }
        });

        ll_putong_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoleController.getInstance().deliverGoodsOperate();
            }
        });

        ll_zhaoche_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(FindCarDeliveryListActivity.class);
            }
        });

        ll_youzhi_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoleController.getInstance().deliverGoodsOperate();
            }
        });


        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestVehicleNearby();
                refreshStatisticsView();
                requestUserInfo();
            }
        });





        //扫一扫
        tv_qrcode_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionHelper permissionHelper = new PermissionHelper();

                permissionHelper.checkPermissions(getActivity(), Manifest.permission.CAMERA, new OnPermissionCheckResult() {
                    @Override
                    public void grantedResult() {
                        CustomCaptureActivity.start(HomeFragment.this, CustomCaptureActivity.REQUEST_CODE, R.style.XQRCodeTheme_Custom);
//                        OperateController.getInstance().scanQRCode(getActivity());
                    }

                    @Override
                    public void shouldShowRequestPermissionRationale() {

                    }

                    @Override
                    public void grantedForbidResult() {
                        permissionHelper.showPermissionTipDialog(getActivity(), Manifest.permission.CAMERA);
                    }
                });
            }
        });






    }



    @Override
    protected void onUserVisible() {
        super.onUserVisible();
        //是否需要显示认证状态
        requestUserInfo();
    }

    private void stopRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void requestUserInfo() {

        mUserInfoModel.userInfoModel(getContext(), false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<UserInfo>>() {

            @Override
            public void onNext(CommonResponse<UserInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    UserInfo userInfo = commonResponse.getData();
                    if (userInfo != null && userInfo.profile != null) {
                        userAccount = userInfo.profile.account;
                        RoleController.getInstance().setRole(userInfo.profile);
                        //认证状态
                        mAuthStatusView.showAuthStatus(userInfo);

                        SharedPreferenceManager.getInstance().setConsignorId(userInfo.profile.id);
                        SharedPreferenceManager.getInstance().setConsignorName(userInfo.profile.name);
                        SharedPreferenceManager.getInstance().setPhone(userInfo.profile.phone);

                        rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                        if (2== rolePosition){
                            //2 销售，3物流
                            ll_putong_send.setVisibility(View.GONE);
                            ll_zhaoche_send.setVisibility(View.VISIBLE);
//                            initChangeFragment(ToExamineListFragment.newInstance(new ToExamineStatus()));
                        }else {
                            ll_putong_send.setVisibility(View.VISIBLE);
                            ll_zhaoche_send.setVisibility(View.GONE);
//                            initChangeFragment(SourceDocumentListFragment.newInstance(new SourceStatus()));
                        }



                        if (2== rolePosition){
                            //2 销售，3物流
//                                getJiSuanList();
                            iv_more.setVisibility(View.GONE);
                            tv_all_num.setVisibility(View.GONE);
                        }else {
                            requestConsignorGroupListInfo(userInfo.profile.id);
                        }
                        if (firstShow){
                            firstShow=false;

                            initListView();
                        }
                    }
                    VehicleFrontActivity.getXinDIInfo(getActivity());

                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }



    private void requestStatisticsData() {
        String date;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        date = df.format(calendar.getTime());
        requestOrderStatisticsInfo(date);
        requestDriverCarStatisticsInfo(date);
    }

    private void requestOrderStatisticsInfo(String date) {
        Map<String, String> map = new HashMap<>();
        map.put("dates", date);
        mUserInfoModel.orderStatisticsInfoModel(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<OrderStatisticalInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<OrderStatisticalInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    List<OrderStatisticalInfo> list = commonResponse.getData();
                    showOrderStatisticsInfo(list);

                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }

    private void showOrderStatisticsInfo(List<OrderStatisticalInfo> orderStatisticalInfoList) {
        if (orderStatisticalInfoList != null && orderStatisticalInfoList.size() > 0) {
            int size = orderStatisticalInfoList.size();
            OrderStatisticalInfo orderStatisticalInfo;
            OrderStatisticalInfo TJOrderStatisticalInfo = null;
            OrderStatisticalInfo HBOrderStatisticalInfo = null;
            for (int i = 0; i < size; i++) {
                orderStatisticalInfo = orderStatisticalInfoList.get(i);
                if (!TextUtils.isEmpty(orderStatisticalInfo.belongarea) && orderStatisticalInfo.belongarea.equals("1")) { //河北
                    HBOrderStatisticalInfo = orderStatisticalInfo;
                } else if (!TextUtils.isEmpty(orderStatisticalInfo.belongarea) && orderStatisticalInfo.belongarea.equals("2")) { //天津
                    TJOrderStatisticalInfo = orderStatisticalInfo;
                }
            }
            if (TJOrderStatisticalInfo != null && HBOrderStatisticalInfo != null) {
                String totalOrderValue;
                totalOrderValue = new BigDecimal(TJOrderStatisticalInfo.total).add(new BigDecimal(HBOrderStatisticalInfo.total)).toString();
                String totalAmountValue;
                totalAmountValue = new BigDecimal(TJOrderStatisticalInfo.amountTotal).add(new BigDecimal(HBOrderStatisticalInfo.amountTotal)).toString();

                statisticsDataInfo.allOrder = totalOrderValue;
                statisticsDataInfo.allAmount = totalAmountValue;
                mStatisticsDataView.setStatisticsViewData(statisticsDataInfo);
            }
        }
    }

    private void requestDriverCarStatisticsInfo(String date) {
        Map<String, String> map = new HashMap<>();
        map.put("dates", date);
        mUserInfoModel.driverCarStatisticsInfoModel(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<DriverCarStatisticalInfo>>() {
            @Override
            public void onNext(CommonResponse<DriverCarStatisticalInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    DriverCarStatisticalInfo info = commonResponse.getData();
                    showDriverAndCarStatisticsInfo(info);
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }

    private void showDriverAndCarStatisticsInfo(DriverCarStatisticalInfo info) {
        String totalDriver = new BigDecimal(info.drivertotal).add(new BigDecimal(info.yesdrivertotal)).toString();
        String totalCar = new BigDecimal(info.drivercartotal).add(new BigDecimal(info.yesdrivercartotal)).toString();
        statisticsDataInfo.allDriver = totalDriver;
        statisticsDataInfo.allCar = totalCar;
        mStatisticsDataView.setStatisticsViewData(statisticsDataInfo);

    }

    private void requestVehicleNearby() {
        firstShow=true;
        requestUserInfo();
        stopRefresh();
//        mUserInfoModel.vehicleNumberModel(getContext(), false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<VehicleNearbyInfo>>() {
//            @Override
//            public void onNext(CommonResponse<VehicleNearbyInfo> commonResponse) {
//                stopRefresh();
//                if (commonResponse.getCode() == 20000) {
//                    VehicleNearbyInfo nearbyInfo = commonResponse.getData();
//                    if (nearbyInfo != null) {
//                        mVehicleTotalNumberTextView.setText(nearbyInfo.CarTotal);
//                        mTipTextView.setText("您周边有" + CommonUtil.keepTwoDecimal(StringUtils.toFloat(nearbyInfo.nearCarTotal) / 10000 + "") + "万+车辆为您服务");
////                        mTipTextView.setText("您周边有" + "40.54"+ "万+车辆为您服务");
//                    }
//                }
//
//            }
//
//            @Override
//            public void onError(ExceptionHandle.ResponseThrowable responseThrowable) {
//                stopRefresh();
//            }
//        });
    }

    private List<OrderOperateInfo> getOperateList() {
        List<OrderOperateInfo> list = new ArrayList<>();
        OrderOperateInfo operateInfo;
        operateInfo = new OrderOperateInfo();
        operateInfo.operate = "货源单";
        operateInfo.operateImageId = R.mipmap.icon_source_home;
        list.add(operateInfo);
        operateInfo = new OrderOperateInfo();
        operateInfo.operate = "调度单";
        operateInfo.operateImageId = R.mipmap.icon_dispatch_home;
        list.add(operateInfo);
        operateInfo = new OrderOperateInfo();
        operateInfo.operate = "运费计算";
        operateInfo.operateImageId = R.mipmap.icon_freight_home;
        list.add(operateInfo);
        operateInfo = new OrderOperateInfo();
        operateInfo.operate = "付款申请";
        operateInfo.operateImageId = R.mipmap.icon_payment_home;
        list.add(operateInfo);

        return list;
    }


    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_CONSIGNOR_INFO:
                requestVehicleNearby();
                break;
            case EVENT_REFRESH_STATISTICS_VIEW:
                refreshStatisticsView();
                break;
        }
    }

    private void refreshStatisticsView() {
        boolean isShowStatisticsView = RoleController.getInstance().isShowStaticsView();
        if (isShowStatisticsView) {
            mStatisticsDataView.setVisibility(View.VISIBLE);
            requestStatisticsData();
        } else {
            mStatisticsDataView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.fragment_home_statisticsDataView)
    public void statisticsInfo() {
        openActivity(DisplayDataActivity.class);
    }

    @OnClick(R.id.tv_all_num)
    public void setHuoQuan() {
        if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KeyValue.KEY_CONSIGNOR_LIST, mConsignorInfoList);
            openActivity(ConsignorListActivity.class, bundle);
        }
    }

    @OnClick(R.id.iv_more)
    public void setHuoQuanTwo() {
        if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KeyValue.KEY_CONSIGNOR_LIST, mConsignorInfoList);
            openActivity(ConsignorListActivity.class, bundle);
        }
    }



    ////=====列表======
    private void requestDataList(int page, boolean isDialog) {

        OrderCondition orderCondition = new OrderCondition();
        orderCondition.page = page;
        orderCondition.searchKey = "";
        Observable orderListObservable = getOrderListObservable(orderCondition);
        requestOrderList(orderListObservable,true);

        //刷新货权数量
        if (3== rolePosition){
            //2 销售，3物流
            String consignorId = SharedPreferenceManager.getInstance().getConsignorId();
            requestConsignorGroupListInfo(consignorId);
        }

    }


    private Observable getOrderListObservable(OrderCondition orderCondition) {


        if (2== rolePosition){
            //2 销售，3物流
            Map<String, String> map = new HashMap<>();
            map.put("limit", "10");
            map.put("offset", "0");
            map.put("status", "0");//0 待审核，1 已审核 2拒绝
            map.put("order", "desc");
            map.put("sort", "id");
            map.put("page", orderCondition.page + "");
            return CommonConfig.getInstance().create(OrderApiService.class).toExamine(map);
        }else {
            Map<String, String> map = new HashMap<>();
            map.put("limit", "3");
            map.put("offset", "1");
            map.put("order", "desc");
            map.put("billtype", "0");//1 外部 0，空是货源
            map.put("sort", "create_time");
            map.put("isstatus", "1");
            map.put("page", orderCondition.page + "");
            return CommonConfig.getInstance().create(OrderApiService.class).sourceList(map);
        }

    }

    private OrderModel mModel;
    private void requestOrderList(Observable observable, boolean isDialog) {
        if (null==mModel){
            mModel = new OrderModel();
        }
        mModel.orderListModel(getActivity(), observable, isDialog, bindLifecycle(), new ObserverResponseListener<CommonResponse<CommonDataListInfo>>() {
            @Override
            public void onNext(CommonResponse<CommonDataListInfo> commonResponse) {
                if (null != getView()) {
                    processOrderListResult(commonResponse);
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                if (null != getView()) {
                    setMsg(e.message);
                    stopRefresh();
                }
            }
        });
    }

    private void processOrderListResult(CommonResponse<CommonDataListInfo> baseResponse) {
        if (baseResponse.getCode() == 20000) {
            CommonDataListInfo data = baseResponse.getData();
            setPageInfo(data.current, data.pages);
            List<OrderInfo> list = data.records;
            if (list != null && list.size() > 0) {
                showDataList(list);
            } else {

//                showDataList(list);
//                stopRefresh();
                showEmptyView();
            }
        } else {
            setMsg(baseResponse.getMsg());
            stopRefresh();
        }
    }

    public void setPageInfo(int currentPage, int totalPage) {
        mPage = currentPage;
        mTotalPage = totalPage;
    }


    public void showDataList(List data) {
        if (mAdapter == null) return;
        if (isRefresh) {
            mAdapter.clear();
            isRefresh = false;
        }
        mAdapter.addAll(data);
    }

    public void showEmptyView() {

        if (isRefresh) {
            isRefresh = false;
        }

        if (mRecyclerView == null) return;

        mRecyclerView.setEmptyView(com.fgs.common.R.layout.layout_empty_view);
        mRecyclerView.showEmpty();
        View emptyView = mRecyclerView.getEmptyView();
        if (emptyView != null) {
            int imageId = com.fgs.common.R.mipmap.icon_empty_route;
            if (imageId != 0) {
                emptyView.findViewById(com.fgs.common.R.id.layout_empty_view_imageView).setBackgroundResource(com.fgs.common.R.mipmap.icon_empty_route);
            }
            TextView textView = mRecyclerView.getEmptyView().findViewById(com.fgs.common.R.id.layout_empty_view_textView);
            String content = "";
            if (!TextUtils.isEmpty(content)) {
                textView.setText(content);
            }
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSendMsg(CommonEvent event) {
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_ORDER_LIST:
//                String message = event.getMessage();
//                refreshData(true);
                isRefresh = true;
                requestDataList(1, false);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理二维码扫描结果
        if (requestCode == CustomCaptureActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            //处理扫描结果（在界面上显示）
            handleScanResult(data);
        }
    }


    /**
     * 处理二维码扫描结果
     *
     * @param data
     */
    private void handleScanResult(Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                    String result = bundle.getString(XQRCode.RESULT_DATA);
                    try {
                        //6c585c1d-b0ce-68e5-b68b-cb9969b224d3
//                        String[] split = result.split("-");
//                        Toast.makeText(getActivity(), ""+result, Toast.LENGTH_SHORT).show();
                        setCodeLogin(result);
//                        if (split.length>3){
//
//                            bundle.putString(KeyValue.KEY_FOLLOW_CONSIGNORID, split[1]);
//                            bundle.putString(KeyValue.KEY_FOLLOW_ROLEID, split[2]);
//                            bundle.putString(KeyValue.KEY_FOLLOW_CONSIGNORNAME, split[3]);
//                            openActivity(FollowActivity.class, bundle);
//
//                        }else {
//                            String billNo = Base64Utils.decode(result);
//                            String string = billNo.substring(1);
//                            if (AppUtils.isNumber(string)) {
//                                bundle.putString(KeyValue.KEY_SHARE_ORDER_ID, billNo);
//                                openActivity(GoodsDetailActivity.class, bundle);
//                            } else {
//                                showToast("请扫描正确的二维码");
//                            }
//                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast("解析二维码失败");
                    }
                } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                    showToast("解析二维码失败");
                }
            }
        }
    }


    private void setCodeLogin(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", userAccount);
        map.put("qrcode", code);
        map.put("confirm", "1");
        mUserInfoModel.setCodeLogin(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
//                    List<OrderStatisticalInfo> list = commonResponse.getData();
//                    showOrderStatisticsInfo(list);

                    Toast.makeText(getActivity(), "扫码成功", Toast.LENGTH_LONG).show();
//                    showToast("success"+commonResponse.getData().toString());
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }




    private ArrayList<ConsignorInfo> mConsignorInfoList;
    //货权选择列表
    private void requestConsignorGroupListInfo(String id) {
        if (TextUtils.isEmpty(id)) return;
        Map<String, String> map = new HashMap<>();
        map.put("userId", id);
        mUserInfoModel.consignorGroupListModel(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<ArrayList<ConsignorInfo>>>() {
            @Override
            public void onNext(CommonResponse<ArrayList<ConsignorInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    mConsignorInfoList = commonResponse.getData();
                    if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {

                        int trueNum=0;
                        int allNum=0;
                        for (int i=0;i<mConsignorInfoList.size();i++){
                            ConsignorInfo consignorInfo = mConsignorInfoList.get(i);
                            allNum+=consignorInfo.counts;

                            if (consignorInfo.isLogin){
                                iv_more.setText(consignorInfo.customer+"("+consignorInfo.counts+")");
                                trueNum++;
                            }
                        }
                        tv_all_num.setText(allNum+"");
                        if (trueNum>2){
                            iv_more.setText("待审核找车单");
                        }

//                        boolean isShow=false;
//                        String title="以下货权有找车单";
//                        String go="去切换";
//                        String text="";
//                        for (int i=0;i<mConsignorInfoList.size();i++){
//                            ConsignorInfo consignorInfo = mConsignorInfoList.get(i);
//                            if (!"0".equals(consignorInfo.counts)){
//                                text=text+consignorInfo.customername+"("+consignorInfo.counts+"单)\n";
//                                isShow=true;
//                            }
//                        }
//                        if (isShow){
//                            ShowDialog(title,text,go);
//                        }

                    }
                } else {
                    LogUtil.print(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
            }
        });
    }

    private void getJiSuanList() {
        Map<String, String> map = new HashMap<>();
//        map.put("limit", "10");
//        map.put("offset", "1");
//        map.put("order", "desc");
//        map.put("sort", "recelvetimeconfirm");
//        map.put("isstatus", "9,12");
//        map.put("page", "1");
//        CommonConfig.getInstance().create(OrderApiService.class).freightList(map);
        mUserInfoModel.getYuQiTipList(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<YuQiTipInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<YuQiTipInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    List<YuQiTipInfo> dataList = commonResponse.getData();
                    if (dataList != null&& dataList.size() > 0) {
                        String title="重要提示";
                        String go="去处理";
                        String text="您有逾期订单待处理，请确认订单状态并尽快处理逾期，否则将影响您的发货权限";
                        ShowDialog(title,text,go);
                    }
                } else {
                    LogUtil.print(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
            }
        });
    }


    //显示提示
    private void ShowDialog(String title, String text,String go){
        new MaterialDialog.Builder(getContext())
                .title(title)
                .content(text)
                .positiveText(go)
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        if (2== rolePosition){
                            //2 销售，3物流
//                            EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_MOVE_TO_JISUAN.getValue()));
                            Intent intent=new Intent(getActivity(), OverdueManageActivity.class);
                            startActivity(intent);
                        }else {
                            EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_MOVE_TO_MINE.getValue()));
                        }
                    }
                })
                .show();
    }



    private void initListView() {
        //列表
        mIOrderStatus=new SourceStatus();
        if (2== rolePosition){
            //2 销售，3物流
            mAdapter = new ToExamineListAdapter(getContext(), mIOrderStatus, rolePosition,1);
        }else {
            mAdapter = new SourceDocumentListAdapter(getContext(),mIOrderStatus );
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        RecycleViewItemLine line = new RecycleViewItemLine(getContext(),
                LinearLayout.HORIZONTAL,
                20,//(int) CommonUtil.convertDpToPixel(10)
                getResources().getColor(R.color.colorGrayOne)
        );
        mRecyclerView.addItemDecoration(line);


        initAdapterListenr();

        mRecyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                refreshOperate();
                mPage = 1;
                isRefresh = true;
                requestDataList(mPage, false);
            }
        });
//        mAdapter.setMore(com.fgs.common.R.layout.layout_load_more, new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                if (mPage < mTotalPage) {
//                    mPage++;
//                    requestDataList(mPage, false);
//                } else {
//                    mAdapter.stopMore();
//                }
//            }
//        });
//        mAdapter.setNoMore(com.fgs.common.R.layout.layout_no_more);

        setPageInfo(1, 1);
        requestDataList(mPage, false);
    }


    private void  initAdapterListenr(){
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (2== rolePosition){
                    //2 销售，3物流
                    Object object = mAdapter.getAllData().get(position);
                    if (object instanceof ToExamineInfo) {
                        ToExamineInfo examineInfo = (ToExamineInfo) object;

                        Gson gson=new Gson();
                        String json = gson.toJson(examineInfo);
                        Bundle bundle=new Bundle();
                        bundle.putString("toexamine",json);

//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                    bundle.putString("", mIOrderStatus.getOrderStatusType());

                        if (2==rolePosition){
                            //2 销售，3物流
                            openActivity(FindCarOnlyLookActivity.class, bundle);
                        }else {
                            //0 待审核、1已经审核 2退回,3作废
                            if ("0".equals(examineInfo.status)){
                                openActivity(CarSearchAuditActivity.class, bundle);
                            } else {
                                openActivity(FindCarOnlyLookActivity.class, bundle);
                            }
                        }
                    }
                }else {
                    Object object = mAdapter.getAllData().get(position);
                    if (object instanceof OrderInfo) {
                        OrderInfo orderInfo = (OrderInfo) object;
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                        bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());

                        if (mIOrderStatus.getOrderStatusType() != OrderType.TYPE_PAYMENT) {
                            openActivity(OrderDetailActivity.class, bundle);
                        }
                    }
                }
            }
        });



        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                if (2 == rolePosition) {
                    Object object2 = mAdapter.getAllData().get(position);
                    ToExamineInfo examineInfo = null;
                    if (object2 instanceof ToExamineInfo) {
                        examineInfo = (ToExamineInfo) object2;
                    }
                    Gson gson=new Gson();
                    switch (view.getId()) {
                        case R.id.tv_quxiao:
                            String json = gson.toJson(examineInfo);
                            GoodsInfo  mGoodsInfo = gson.fromJson(json, GoodsInfo.class);
                            if (examineInfo != null) {
                                showDelete(mGoodsInfo);
                            }
                            break;
                        case R.id.tv_bainji:
                            String json2 = gson.toJson(examineInfo);
                            Bundle bundle=new Bundle();
                            bundle.putString("erpdetails",json2);
                            openActivity(EditFindCarLiteDeliverActivity.class,bundle);
                            break;
                    }

                } else {
                    Object object = mAdapter.getAllData().get(position);
                    OrderInfo orderInfo = null;
                    if (object instanceof OrderInfo) {
                        orderInfo = (OrderInfo) object;
                    }

                    switch (view.getId()) {
//                    case R.id.item_order_list_submitTextView:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                            bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
//                            openActivity(OrderDetailActivity.class, bundle);
//                        }
//
//                        break;
                        case R.id.ll_driver_line_body://分享码
                            if (orderInfo != null) {
                                showShareCode(orderInfo);
                            }
                            break;
                        case R.id.tv_guanli:

                            if (mIOrderStatus != null) {
                                Bundle bundle = new Bundle();
                                bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
                                bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                                openActivity(OrderOperateActivity.class, bundle);
                            }
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString(KeyValue.KEY_ID, orderInfo.id);
//                            openActivity(EditDeliveryGoodsStepOneActivity.class, bundle);
//                        }
                            break;
                        case R.id.tv_tonghua:
                            if (orderInfo != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("sourcenum", orderInfo.billno);
                                openActivity(TongHuaLogActivity.class, bundle);
                            }
//                        Toast.makeText(getContext(), "通话记录", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.tv_liulan:
                            if (orderInfo != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("sourcenum", orderInfo.billno);
                                openActivity(LiuLanLogActivity.class, bundle);
                            }
//                        Toast.makeText(getContext(), "浏览记录", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.iv_zhongzhi:
                            ZhongZhiDingDan(orderInfo);
                            break;
                        case R.id.tv_zhuan:
                            zhuanZhaoChe(orderInfo);
                            break;


                    }
                }
            }
        });

    }

    private void ZhongZhiDingDan(OrderInfo orderInfo) {
        new OperateTipDialog.Builder(getActivity())
                .title("请输入原因")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入终止原因");
                            return;
                        }
                        dialog.dismiss();
                        Map<String, String> map = new HashMap<>();
                        map.put("billno", orderInfo.billno);
                        map.put("remark", reason);
                        map.put("isstate", "11");
                        new OrderRequestOperate().orderOperateRequest(getActivity(), map,orderInfo.dingJinType ,
                                new OrderOperateCallback() {
                                    @Override
                                    public void operateCallback() {
                                        ToastUtil.showShortToast("单据终止成功");
//                                        showTerminateResultDialog(getActivity(), "单据终止成功", operateInfo);
                                        EventBusManage.refreshOrderList();
                                        EventBusManage.activityFinish();
                                    }

                                    @Override
                                    public void onFailed(String message) {

                                    }
                                });
                    }
                })
                .show();
    }

    private void showShareCode(OrderInfo orderInfo) {
        new PermissionHelper().checkPermissions((FragmentActivity) getContext(), new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {

                if (!TextUtils.isEmpty(orderInfo.billno)) {
                    String base64BillNo = Base64Utils.encode(orderInfo.billno);
                    Bitmap bitmap = createQRCodeWithLogo(base64BillNo, ImageUtils.getBitmap(R.mipmap.icon_app));
                    new QRCodeDialog(getContext(), bitmap).show();
                } else {
                    showToast("获取订单信息失败");
                }

            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    /**
     * 生成简单的带logo的二维码
     *
     * @param content
     * @param logo
     */
    @IOThread(ThreadType.Single)
    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
        return bitmap;
    }


    private void zhuanZhaoChe(OrderInfo orderInfo) {
        new MaterialDialog.Builder(getContext())
                .content("确定要转为外部单吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Map<String, String> map = new HashMap<>();
                        map.put("billno", orderInfo.billno);
                        map.put("billtype", "1");
//        map.put("isstate", "11");
                        new OrderRequestOperate().ZhuanZhaoChe(getActivity(), map,orderInfo.dingJinType ,
                                new OrderOperateCallback() {
                                    @Override
                                    public void operateCallback() {
                                        ToastUtil.showShortToast("转单成功");
//                                        showTerminateResultDialog(getActivity(), "单据终止成功", operateInfo);
                                        EventBusManage.refreshOrderList();
//                        EventBusManage.activityFinish();
                                    }

                                    @Override
                                    public void onFailed(String message) {

                                    }
                                });
                    }
                })
                .show();
    }


    private void showDelete(GoodsInfo  mGoodsInfo) {
        new MaterialDialog.Builder(getContext())
                .content("确定要删除找车单吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                        tongYiFaDan(mGoodsInfo);
                    }
                })
                .show();
    }

    private void tongYiFaDan(GoodsInfo mGoodsInfo) {

        GoodsModel mModel = new GoodsModel();
        BoHuiBodyBean boHuiBodyBean = new BoHuiBodyBean(mGoodsInfo.id, "删除", "4");

        mModel.boHuiZhaoChe(getActivity(), boHuiBodyBean, true, bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {

                    EventBusManage.refreshOrderList();

                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });
    }




}
